package com.wz.leetcode.backtrack;

import java.util.*;

public class Permutations2_47 {
    public static List<List<Integer>> permuteUnique(int[] nums) {
        int len = nums.length;
        List<List<Integer>> result = new ArrayList<>();
        if (len == 0) {
            return result;
        }
        // 排序是剪枝的前提
        Arrays.sort(nums);
        boolean[] used = new boolean[len];
        Deque<Integer> path = new ArrayDeque<>(len);
        dfs(nums, len, 0, used, path, result);
        return result;
    }

    private static void dfs(int[] nums,
                            int len,
                            int index,
                            boolean[] used,
                            Deque<Integer> path,
                            List<List<Integer>> result) {
        if (index == len) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < len; ++i) {
            if (!used[i]) {
                // 写 !used[i - 1] 是因为 nums[i - 1] 在深度优先遍历的过程中刚刚被撤销选择
                if (i > 0 && nums[i] == nums[i-1] && !used[i-1]) {
                    continue;
                }
                path.addLast(nums[i]);
                used[i] = true;
                dfs(nums, len, index + 1, used, path, result);
                used[i] = false;
                path.removeLast();
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(permuteUnique(new int[]{1,1,1}));
        System.out.println(permuteUnique(new int[]{1,1,2}));
        System.out.println(permuteUnique(new int[]{1,2,3}));
    }
}
